package com.xifly.jwt;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.xifly.bean.UserInfo;
import com.xifly.repository.UserInfoRepository;
import com.xifly.utils.MyUtils;
import com.xifly.utils.ResultMsg;
import com.xifly.utils.ResultStatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JsonWebToken {
    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private Audience audience;

    @RequestMapping("/oauth/token")
    public Object getAccessToken(@RequestBody LoginPara loginPara){
        ResultMsg resultMsg;
        try {
            if (loginPara.getClientId () == null || (loginPara.getClientId().compareTo(audience.getClientId()) != 0)){
                resultMsg = new ResultMsg(ResultStatusCode.INVALID_CLIENTID.getErrorcode(),
                        ResultStatusCode.INVALID_CLIENTID.getErrormsg(),null);
                return resultMsg;
            }

            //验证码校验在后面章节添加

            //验证用户名密码
            UserInfo user = userInfoRepository.findUserInfoByName(loginPara.getUserName());
            if (user == null){
                resultMsg = new ResultMsg(ResultStatusCode.INVALID_PASSWORD.getErrorcode(),
                        ResultStatusCode.INVALID_PASSWORD.getErrormsg(),null);
                return resultMsg;
            } else {
                String md5Password = MyUtils.getMD5(loginPara.getPassword() + user.getSalt());

                if (md5Password.compareTo(user.getPassword()) != 0){
                    resultMsg = new ResultMsg(ResultStatusCode.INVALID_PASSWORD.getErrorcode(),
                            ResultStatusCode.INVALID_PASSWORD.getErrormsg(),null);
                    return resultMsg;
                }
            }

            //拼装accessToken
            String accessToken = JwtHelper.createJWT(loginPara.getUserName(),String.valueOf(user.getName()),
                    user.getRole(),audience.getClientId(),audience.getName(),
                    audience.getExpiresSecond() * 1000, audience.getBase64Secret());

            //返回accessToken
            AccessToken accessTokenEntity = new AccessToken();
            accessTokenEntity.setAccess_token(accessToken);
            accessTokenEntity.setExpires_in(audience.getExpiresSecond());
            accessTokenEntity.setToken_type("bearer");
            resultMsg = new ResultMsg(ResultStatusCode.OK.getErrorcode(),ResultStatusCode.OK.getErrormsg(),accessTokenEntity);
            return resultMsg;

        } catch (Exception e){
            resultMsg = new ResultMsg(ResultStatusCode.SYSTEM_ERROR.getErrorcode(),
                    ResultStatusCode.SYSTEM_ERROR.getErrormsg(),null);
            return resultMsg;
        }

    }
}
